package com.fingard.dsp.bank.directbank.cgb02.receiptPro;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDataHelper;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.abc02.ABC02ReceiptPro;
import com.fingard.dsp.bank.directbank.cgb02.CGB02Base;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.dsp.bank.sepro.ReceiptPro;
import com.fingard.dsp.task.DelayCounter;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.FGBiz;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

/**
 * @Description TODO
 * @Author xtt
 **/
public class CGB02TaskReceiptPro extends CGB02Base {
    private String logCode = "CGB02" + File.separator + "TaskReceiptPro";
    private TaskTimerSet timerSet;
    private ReceiptProConfig proConfig;
    //private boolean byLocalhost;

    private static DelayCounter delayCounter = new DelayCounter(45, 2);//最大延时45分钟，按平方计算，即4次=4*4=16分钟

    public static void resetDelayCounter() {
        delayCounter.resetZeroCount();
    }

    public void downReceipt(TaskTimerSet pTimerSet) {
        try {
            timerSet = pTimerSet;

            proConfig = ReceiptPro.getReceiptProConfig();
            //byLocalhost = false;
            String beginDate = timerSet.taskParams.get("begindaycount");
            String endDate = timerSet.taskParams.get("enddaycount");
            downlaodForSftpAndInsert(beginDate, endDate);

        } catch (Exception e) {
            FGBiz.logTrace.exception(logCode, e);
        }
    }

    /**
     * sftp方式回单获取
     *
     * @return
     */
    public void downlaodForSftpAndInsert(String beginDate, String endDate) throws IOException {
        SftpPortClient sftpPortClient = null;
        try {
            String qryBeginDay = getDate8(beginDate);
            String qryEndDay8 = getDate8(endDate);
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(Format.Date8Format.parse(qryBeginDay));

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(Format.Date8Format.parse(qryEndDay8));
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            //按自然月循环查询
            while (tmpIntDateFrom <= tmpIntDateTo) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                String qryDay8 = Format.Date8Format.format(tmpCalendarFrom.getTime());
                String saveDirPathTemp = proConfig.localSaveMainDir + File.separator + qryDay8;

                FtpSet ftpSet = bankFront.getFtpSet("receipt");
                ftpSet.downDir = StringHelper.trimEnd(ftpSet.downDir, "/") + "/";
                WriteBankLogLn("SFTP下载地址" + ftpSet.serverIP + ":" + ftpSet.port);
                WriteBankLogLn("开始遍历服务器文件目录" + ftpSet.downDir + qryDay8);

                sftpPortClient = new SftpPortClient(ftpSet);
                ArrayList<String> ftpFileList = sftpPortClient.listNames(ftpSet.downDir + qryDay8);
                if (ftpFileList.size() == 1) {
                    WriteBankLogLn("当前日期：" + qryDay8 + "无回单文件");
                    FGBiz.logTrace.info(logCode, "当前日期：" + qryDay8 + "无回单文件");
                }

                FtpReceiver ftpReceiver = sftpPortClient.downloadFile(ftpSet.downDir + qryDay8, saveDirPathTemp);
                File tmpFile = new File(saveDirPathTemp);
                File[] files = tmpFile.listFiles();
                int[] retVals = new int[3];
                retVals[0] = 0;//总pdf个数
                retVals[1] = 0;//新增
                retVals[2] = 0;//已存在
                for (File file : files) {
                    String ftpFileName = file.getName();
                    if (ftpFileName.contains(".txt")) {
                        WriteBankLogLn("解析汇总文件:" + ftpFileName);
                        //保存路径
                        if (ftpReceiver.isCompleted) {

                            //解析汇总文件返回map
                            String[] line = FileHelper.readFileText(saveDirPathTemp, "UTF-8").split("\n|\r");
                            int totalFiles = 0;
                            //读取文件内容
                            for (String pfiles : line) {
                                if (!pfiles.contains("\\|")) {
                                    totalFiles = Integer.valueOf(pfiles);
                                } else {
                                    //入库
                                    String[] receiptInfo = pfiles.split("\\|");
                                    ReceiptData eachData = new ReceiptData();
                                    eachData.bank = "";
                                    eachData.srcSys = "CGB02";
                                    eachData.localFile = saveDirPathTemp + File.separator + receiptInfo[1] + ".pdf";
                                    eachData.receiptNo = receiptInfo[1];
                                    eachData.busDate = Integer.parseInt(qryDay8);
                                    eachData.bnkSeqNo = receiptInfo[1] + receiptInfo[0] + getBeforeDay(qryDay8);
                                    if (receiptInfo[4].contains("D")) {
                                        eachData.moneyWay = "1";
                                    } else if (receiptInfo[4].contains("C")) {
                                        eachData.moneyWay = "2";
                                    }
                                    eachData.downState = "2";
                                    eachData.downTime = new Date();
                                    ReceiptDataHelper receiptHelper = new ReceiptDataHelper(reqHeader.tenant, eachData.getBusDate());
                                    int inRe = receiptHelper.insertIfNotExist(eachData, true);
                                    if (inRe > 0) {
                                        retVals[1] = retVals[1] + 1;
                                    } else if (inRe == 0) {
                                        retVals[2] = retVals[2] + 1;
                                    }
                                    WriteBankLogLn(eachData.receiptNo + "写入数据库，影响行数：" + inRe);
                                    FGBiz.logTrace.info(logCode, eachData.receiptNo + "写入数据库，影响行数：" + inRe);

                                }
                            }
                        } else {
                            WriteBankLogLn(ftpFileName + "回单文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState);
                            FGBiz.logTrace.error(logCode, ftpFileName + "回单文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState);
                        }
                    }
                }

                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            WriteBankLogLn(ex);
        } finally {
            if (sftpPortClient != null) {
                sftpPortClient.disconnect();
            }
        }
    }

    public String getDate8(String beginDays) {
        SimpleDateFormat dft = new SimpleDateFormat("yyyyMMdd");
        Date beginDate = new Date();
        Calendar date = Calendar.getInstance();
        date.setTime(beginDate);
        if (beginDays != null && beginDays.contains("-")) {
            int days = Integer.valueOf(beginDays.replace("-", ""));
            date.set(Calendar.DATE, date.get(Calendar.DATE) - days);
        }
        return dft.format(date.getTime());
    }

    public String getBeforeDay(String day) throws Exception {
        SimpleDateFormat dft = new SimpleDateFormat("yyyyMMdd");
        Date beginDate = Format.Date8Format.parse(day);
        Calendar date = Calendar.getInstance();
        date.setTime(beginDate);
        date.set(Calendar.DATE, date.get(Calendar.DATE) - 1);
        return dft.format(date.getTime());
    }

}
